using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Collections.Specialized;

namespace FontKonverter {
    public class LegacyConverter : IConverter {
        #region IConverter Members
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sin">as reordered unicode string based on legacy style
        //    data the font data for the conversion</param>
        /// <returns>legacy string where unkown unicode codepoints are dropped</returns>
        public string Converter(string sin, ArrayList lookupData) {
            StringBuilder sout = new StringBuilder();
            //StringDictionary dicts = lookupData[0] as StringDictionary; //# dictionary not in unicode range
            List<StringDictionary> dicts = (List<StringDictionary>)lookupData[0];
            string[] replaceData = (string[])lookupData[1]; //# list with character replacement values
            
            int listLength = replaceData.Length;
            int i = 0;
            int end = sin.Length;

            while (i < end) {
                //HACK: dicts[0] has key length = 1, dicts[1] has key length = 2 so on...
                for (int j = 0; j < dicts.Count; j++) {
                    //Console.WriteLine(string.Format("i = {0}, j = {1}", i, j));
                    if (dicts[j].Count == 0)
                        continue;

                    try {
                        string key =sin.Substring(i, j + 1);
                        //Console.WriteLine(string.Format("sin.Substring(i, j + 1) = {0} | dicts[j][sin.Substring(i, j + 1)]={1}", key, dicts[j][key]));
                        if (dicts[j].ContainsKey(key)) {
                            sout.Append(dicts[j][key]);
                            //HACK > ... further investigate ...
                            if (j + 1 == end)
                                i = j + 1;
                            else
                                i += j;
                            break;
                        }
                        continue;
                    } catch {
                        continue;
                    }


                }
                
                //HACK: to be confirm
                if (i < end) {
                    char c = sin[i];
                    int n = c - 0x1780;
                    if (n >= 0 && n < listLength)
                        sout.Append(replaceData[n]);
                    else if (c < 0x7f)  //# keep ascii characters
                        sout.Append(c);

                    i += 1;
                }
            }

            return sout.ToString();
        }

        #endregion
    }
}
